Ext.ns('TaxonTagger');
TaxonTagger.taggerpanel = function(config){
	this.myArray=[];
	var storeRecord = Ext.data.Record.create([
		{name: 'url'}
	]);

	var urlListStore = new Ext.data.ArrayStore({
			fields: ['url']
		,	data: [
					['http://www.bioline.org.br/abstract?id=fb95003']
			]
		,	listeners: {
				load: function(){
					var urlList = Ext.decode(localStorage.getItem("storedUrls"));
					Ext.each(urlList, function(item){
						var newRecord = new storeRecord({
							url: item
						});
						this.insert(this.getCount(), newRecord);
					}, this);
					this.commitChanges();
				}
			}
	});

	this.urlCombo = new Ext.form.ComboBox({
			store: urlListStore
		,	displayField: 'url'
		,	typeAhead: true
		,	mode: 'local'
		,	triggerAction: 'all'
		,	emptyText: 'enter or select a url...'
		,	selectOnFocus: true
		,	allowBlank: false
		,	blankText: 'Please select or enter url.'
		,	vtype: 'url'
		,	urlText: 'enter valid url'
		,	width: 300
	});

	Ext.apply(this, config, {
			id: 'mifp'
		,	border: false
		,	region: 'center'
	//	,	loadMask:{hideOnReady :false,msg:'Loading Site...'}
		,	scope: this
		,	autoScroll: true
		,	tbar: [
					'URL: '
				, this.urlCombo
				, {
						text: 'Load'
					,	iconCls: 'icon_load'	
					,	scope: this 
					,	handler: function() {
							this.loadDocument( this.urlCombo.getValue() );
						}
			}, {
					text: 'Mark Scientific Name'
				,	iconCls: 'icon_mark'
				,	ref: '../markScientificName'
				,	scope: this
				,	hidden: true
				,	handler: function() {
						sel = Ext.getCmp('mifp').getFrameWindow().document.getSelection();
						if (!Ext.isEmpty(sel)) {
							var selectedArray = this.addElementToArray(sel.trim());
							selectedArray = selectedArray.concat(this.customsWord);
							this.markSciName(sel);
							var url = this.urlCombo.getValue();
							this.saveCustomsWords(url, selectedArray);
						}
					}
			}]
		,	listeners: {
						documentloaded: function(frame) {
							frame.unmask();
							
							this.addIframeListeners(frame);
						}
					}	
	});
	
	TaxonTagger.taggerpanel.superclass.constructor.call(this, config);
	
};

Ext.extend(TaxonTagger.taggerpanel, Ext.ux.ManagedIFramePanel, {
	
		addElementToArray : function(newElement){
			this.myArray[this.myArray.length]=newElement;
			return this.myArray;
		}
	,	markSciName : function(sel){
			if (sel == '') return;
			var b = Ext.getCmp('mifp').getFrameWindow().document.body;
			var rg = new RegExp(sel, "ig");
			b.innerHTML = b.innerHTML.replace(rg, "<span class=\"tt-sciname manual\" type='manual'scientificName='" + sel + "'verbatim='" + sel + "' full='" + sel + "' offset='-1'>" + sel + "</span>"+
				"<span class=\"tt-remove manual\" title=\"This removes the scientific name from the list.\">&nbsp;&nbsp;</span>");
			this.generateList();	
		}	
	,	loadCustomsWords : function(url){
			var tConfig = Ext.decode( localStorage.getItem("customWords-" + url) ) || {};
			if (tConfig.customWords == undefined) {
				return [];
			}
			else {
				return tConfig.customWords;
			}
		}
	,	saveCustomsWords : function(url, selectedArray){
			var tConfig = Ext.decode( localStorage.getItem("customWords-" + url) ) || {};
			tConfig.customWords = selectedArray;
			localStorage.setItem("customWords-" + url, Ext.encode(tConfig) );
		}	
	,	customsWords : function(url){
			this.customsWord = this.loadCustomsWords(url);
			for(i = 0; i< this.customsWord.length; i++){
				sel = this.customsWord[i];
				this.markSciName(sel);
			}
		}
				
	,	mark: function(o, success, res, request) {
			if (success) {
				this.comboStore(request.params.url);
				this.cssStyle();
				this.removeSciName();
				this.generateList();
				this.markScientificName.show();
				this.fireEvent('afterDocumentLoaded', this, request.params.url);
				this.customsWords(request.params.url);
				Ext.getCmp('gridpanel').pagingBar.items.items[12].show()
			} else {
				TaxonTagger.Notice.msg('Notice', 'Document request was not successful.');
			}
		}

	,	isURL: function(s) {
			var regexp = /http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/;
			return regexp.test(s);
		}

	,	cssStyle: function(){
			css = new Ext.ux.ManagedIFrame.CSS(this.getFrameDocument());
			css.createStyleSheet('.tt-remove {'+ 
				'background: #FFFF99 url(resources/images/cancel.png) no-repeat 0 3px;'+
				'cursor: pointer;'+	
				'-moz-border-radius-bottomright: 3px;'+
				'-moz-border-radius-topright: 3px;'+	
				'padding-right: 3px;}'
			);
			css.createStyleSheet('.tt-sciname {'+ 
				'-moz-border-radius-bottomleft:3px;'+
				'-moz-border-radius-topleft:3px;'+
				'background-color:#FFFF99;'+
				'color:red;'+
				'cursor:default;'+
				'padding-left:3px;'+
				'padding-right:5px;}'
			);
			css.createStyleSheet('.manual {'+ 
				'background-color:#FF6600 !important;'+
				'color: #FFFFFF !important;}'
			);
		}
		
	,	loadDocument: function(url){
			if (Ext.isEmpty(url)) {
				this.setSrc('blank.html');
				TaxonTagger.Notice.msg('Notice', 'enter or select url');
			}	else if (!this.isURL(url)) {
				this.setSrc('blank.html');
				TaxonTagger.Notice.msg('Notice', 'Please enter valid url');
			}	else {
				this.load({
						url: '../../resources/api/transform.php'
					,	params: {
							url: url
						}
					,	loadMask: "Loading..."
					,	timeout: 60
					,	scope: this
					,	callback: this.mark
				});
				var task = new Ext.util.DelayedTask(function(){
					Ext.getCmp('mifp').getFrame().mask("Analyzing...", 'ext-el-mask-msg x-mask-loading', 'ext-el-mask');
				});
				task.delay(100); 
			}	
		}

	,	comboStore: function( url ){
			if (typeof(localStorage) == 'undefined' ) {
//				TaxonTagger.Notice.msg('Notice', 'Your browser does not support HTML5. Try upgrading.');
			} else {
				var tA = Ext.decode(localStorage.getItem("storedUrls")) || [];
				if (!tA.inArray( url )) {
					tA.unshift(url);
					localStorage.setItem("storedUrls", Ext.encode(tA) );
				}
			}
		}

	,	removeSciName: function(){
			var f = this.getFrameDocument().body;
			Ext.fly(f).on('click', function(e, target) {
				var o = Ext.fly( this );
				var txt = o.prev().dom.innerHTML;	
				Ext.each(Ext.getCmp('mifp').getFrame().select('span.tt-remove').elements, function() {
					var o2 = Ext.fly( this );
					if (o2.prev().dom.innerHTML == txt) {
						Ext.DomHelper.insertBefore(o2.prev(), txt);
						o2.prev().remove();
						o2.remove();
					}
				});
				Ext.DomHelper.insertBefore(o.prev(), txt);
				o.prev().remove();
				o.remove();
				Ext.getCmp('mifp').generateList();
 			}, null, {delegate:'span.tt-remove'});
		}

	,	generateList: function() {
			var i = 0;
			var list = '';
			var gridData = [];						
			this.getFrame().select('span.tt-sciname').each(function( el ) {
				var full = '';
				var offset = '';
				var type = '';
				var verbatim = '';
				var id = '';
				var Ct = '';
				Ext.each( el.dom.attributes, function( item ) {
					
					switch(this.nodeName) {
						case 'full':
							full = this.nodeValue;
							break;
						case 'offset':
							offset = this.nodeValue;
							break;
						case 'type':
							type = this.nodeValue;
							break;
						case 'verbatim':
							verbatim = this.nodeValue;
							break;
						case 'id':
							id = this.nodeValue;						
							break;
						default:
							break;
					}
				});
				
				
				if (type == "" || full == "") {
					type = 'TaxonFinder';
					full = verbatim;
				}	
			
				list += full + "|" + this.dom.innerHTML + '|' + type + '<br>';
				i++;
				var tConfig = Ext.decode( localStorage.getItem("comments-" + this.dom.innerHTML) ) || {};
				gridData.push({
						offset: offset
					,	full: full
					,	orig: this.dom.innerHTML
					,	source: type
					,	verbatim: verbatim
					,	id: id
					,	Ct: tConfig.comment
				});
			});
			Ext.getCmp('gridpanel').store.proxy = new Ext.ux.data.PagingMemoryProxy(gridData);
			Ext.getCmp('gridpanel').store.load({params:{start:0, limit:30}});
	//		Ext.getCmp('list-delimited').body.update( "<div class='list'>" + list + "<div>" );
		//	Ext.getCmp('white-list').loadList(gridData);
		}
	,	addIframeListeners : function(frame) {
			var el = frame.getDoc();
			el.on('contextmenu', function(e, targetEl){
				var sel = Ext.getCmp('mifp').getFrameWindow().document.getSelection();
				var f = Ext.getCmp('mifp').getFrameDocument().body;
				var pXY = this.getXY();
				var xy = e.getXY();
				if(this.menu) this.menu.destroy();
				this.menu = new Ext.menu.Menu({
					items: [{
						text: 'Add '+ sel
					,	ref: 'addAuthor'
					,	scope: this	
					,	hidden: true
					,	handler: function(){
							Ext.each(Ext.fly(f).select("span.tt-sciname").elements, function(el){
								if(targetEl.innerHTML == el.innerHTML){
									var authorship = document.createAttribute('authorship');
									authorship.nodeValue = sel;
									Ext.get(targetEl).addClass('authorship');
									el.attributes.setNamedItem(authorship);
								}
							});
						}  
					}, {
						ref: 'replaceAuthor'	
					,	scope: this	
					,	hidden: true	
					,	handler: function() { 
							Ext.each(Ext.fly(f).select("span.tt-sciname").elements, function(el){
								if(targetEl.innerHTML == el.innerHTML){
									var authorship = document.createAttribute('authorship');
									authorship.nodeValue = sel;
									el.attributes.setNamedItem(authorship);
								}
								
							});
						}
					},{
						ref: 'removeAuthor'	
					,	scope: this	
					,	hidden: true	
					,	handler: function() { 
							Ext.each(Ext.fly(f).select("span.tt-sciname").elements, function(el){
								if(targetEl.innerHTML == el.innerHTML){
									Ext.get(targetEl).removeClass('authorship');
									el.attributes.removeNamedItem('authorship');
								}
								
							});
						}
					}]
				});
				if (!Ext.isEmpty(sel)) {
					var auth = targetEl.getAttribute("authorship");
					if (auth == null) {
						this.menu.addAuthor.show();
					} else if(auth != sel){
						this.menu.replaceAuthor.show();
						this.menu.replaceAuthor.text = 'Replace ' + auth + ' to ' + sel;
					}
				}
				if(targetEl.hasAttribute("authorship")){
					this.menu.removeAuthor.text = 'Remove ' + targetEl.getAttribute("authorship");
					this.menu.removeAuthor.show();
				}
				
				this.menu.showAt(xy);
			}, frame, {
					delegate: 'span.tt-sciname'
				,	stopEvent: true
			});

/*
			el.on('click', function(e,targetEl){
				console.log("Click", e, e.getXY() );																		
				e.preventDefault();
				if(this.menu) this.menu.destroy();
//				e.stopPropagation();
			}, null, {
					stopEvent: false
				,	stopPropagation: false
			});
*/
		}
	
	
});